package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO sumbit(OrdersSubmitDTO ordersSubmitDTO) {
        // 查找当前用户 地址
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        // 地址为空 抛异常
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 把userid赋值给shoppingCart
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        // 用userid查找购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        // 判断购物车是否为0
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        /* 组装*/
        // 组装订单数据插入订单表
        Orders orders = new Orders();
        //补齐字段
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(System.currentTimeMillis() + "");
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 通过地址ID查到的地址，赋值给订单表里的phone Address Consignee
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        //将数据插入到订单表
        orderMapper.insert(orders);

        // 组装订单明细数据插入订单明细表
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        //循环遍历用户购物车 添加到明细表
        for (ShoppingCart cart : shoppingCartList) {
            // 创建新的订单明细
            OrderDetail orderDetail = new OrderDetail();
            // 将商品信息拷贝进订单明细对象
            BeanUtils.copyProperties(cart, orderDetail);
            // 给订单明细添加订单ID   订单表和订单明细表表关系是一对多
            orderDetail.setOrderId(orders.getId());
            // 把单个订单明细对象添加到集合
            orderDetailList.add(orderDetail);
        }
        // 将数据插入到明细表
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.clean(userId);

        // 组装vo返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 用户历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult page(Integer page, Integer pageSize, Integer status) {
        // PageHelper分页查询
        PageHelper.startPage(page, pageSize);
        // 创建OrdersPageQueryDTO 将userid和status赋值进去
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 根据ordersPageQueryDTO中的userid和status去查询
        Page<Orders> pages = orderMapper.page(ordersPageQueryDTO);
        // 定义结合用来存放 OrderVO对象
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        //判断订饭是否为空
        if (pages != null && pages.getTotal() > 0) {
            for (Orders order : pages) {
                // 获得订单ID
                Long orderId = order.getId();
                // 按照订单ID查询订单明细  订单明细存放订单中的菜品
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrederId(orderId);
                // 组装VO对象
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                // 把VO对象添加到集合
                orderVOS.add(orderVO);
            }
        }
        // 组装pageResult对象返回给前端
        PageResult pageResult = new PageResult(pages.getTotal(), orderVOS);
        return pageResult;
    }

    /**
     * 用户端 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderById(Long id) {
        // 查询订单
        Orders orders = orderMapper.getById(id);
        // 查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrederId(orders.getId());
        // 组装vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        // 将vo返回给controller层
        return orderVO;
    }

    /**
     * 用户端 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        // 通过id查询订单
        Orders orderDB = orderMapper.getById(id);

        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // 订单状态不为代付款和待接单时抛异常
        if (orderDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = new Orders();
        order.setId(orderDB.getId());
        // 修改状态为退款
        order.setPayStatus(Orders.REFUND);

        // 修改订单状态
        order.setStatus(Orders.CANCELLED);
        // 取消原因
        order.setCancelReason("用户取消");
        // 取消时间
        order.setCancelTime(LocalDateTime.now());
        // 将修改后的插入订单表
        orderMapper.update(order);
    }

    /**
     * 用户端 再来一单功能
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 查询订单详情数据库
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrederId(id);
        // 遍历所有商品 添加进购物车
        for (OrderDetail orderDetail : orderDetails) {
            // 组装购物车商品对象
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            //将对象插入进购物车
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 管理端订单显示功能
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult adminPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
        // 数据准备
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        // 拿到订单数据
        List<Orders> ordersList = page.getResult();
        for (Orders orders : ordersList) {
            OrderVO orderVO = new OrderVO();
            // 将订单数据拷贝给 vo对象
            BeanUtils.copyProperties(orders, orderVO);
            // 拿到订单ID 并查找到订单里的菜品
            Long ordersId = orders.getId();
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrederId(ordersId);

            List<String> orderDishList = orderDetails.stream().map(x -> {
                String orderDish = x.getName() + "*" + x.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            // 把集合转换为字符串
            String join = String.join("", orderDishList);
            // 组装并将vo对象添加进集合
            orderVO.setOrderDishes(join);
            orderVOS.add(orderVO);
        }
        // 响应数据
        PageResult pageResult = new PageResult(page.getTotal(), orderVOS);
        return pageResult;
    }

    /**
     * 管理端订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 统计状态下的订单条数
        Integer confirmed = orderMapper.countSrats(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countSrats(Orders.DELIVERY_IN_PROGRESS);
        Integer toBeConfirmed = orderMapper.countSrats(Orders.TO_BE_CONFIRMED);

        // 组装VO返回
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 查询订单
        Orders orders = orderMapper.getById(id);
        // 查询订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrederId(id);
        // 组装vo对象
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 商家接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
     /*   // 找到订单id
        Long id = ordersConfirmDTO.getId();

        // 找到订单数据对象 并修改订单状态
        Orders orders = orderMapper.getById(id);
        orders.setStatus(Orders.CONFIRMED);*/
        // 修改订单
        orderMapper.update(orders);
    }

    /**
     * 商家拒单操作
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 找到订单id
        Long id = ordersRejectionDTO.getId();
        // 找到订单数据对象 并修改订单状态和拒单原因
        Orders ordersDB = orderMapper.getById(id);
        if (ordersDB == null || ordersDB.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 组装订单对象
        Orders orders = new Orders();

        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 商家取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        // 找到该订单
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        // 数据准备 写入id 状态 原因 取消时间
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        order.setCancelTime(LocalDateTime.now());
        // 执行修改语句
        orderMapper.update(order);
    }

    /**
     * 商家派送接口
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 找到该订单
        Orders orders = orderMapper.getById(id);
        // 状态不为3(已接单) 报错
        if (orders == null || orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 数据准备
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        // 修改
        orderMapper.update(order);
    }

    /**
     * 商家完成订单操作
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 找到该订单
        Orders orders = orderMapper.getById(id);
        // 状态不为4(派送中) 报错
        if (orders == null || orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 数据准备
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        // 修改
        orderMapper.update(order);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);

        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }


}
